package com.example.flower_shop.repository;

import com.example.flower_shop.entity.Address;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface AddressRepository extends JpaRepository<Address, Long> {
    @Query(value = "SELECT * FROM addresses WHERE user_id = ?1 ORDER BY is_default DESC, create_time DESC", nativeQuery = true)
    List<Address> findByUserId(Long userId);

    Optional<Address> findByIdAndUserId(Long id, Long userId);

    Optional<Address> findByUserIdAndIsDefaultTrue(Long userId);

    @Modifying
    @Query("UPDATE Address a SET a.isDefault = false WHERE a.user.id = ?1 AND a.id != ?2")
    void clearOtherDefaultAddress(Long userId, Long excludeAddressId);

    boolean existsByUserIdAndIsDefaultTrue(Long userId);

    int countByUserId(Long userId);
}